package com.fernfx.xingtan.main.presenter;

import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;

import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.model.LatLng;
import com.fernfx.xingtan.ConsumerApplication;
import com.fernfx.xingtan.R;
import com.fernfx.xingtan.common.base.BaseEntity;
import com.fernfx.xingtan.common.base.BaseView;
import com.fernfx.xingtan.common.network.IRequestCallback;
import com.fernfx.xingtan.common.network.entity.NetworkOKResult;
import com.fernfx.xingtan.main.contract.ChatContract;
import com.fernfx.xingtan.main.entity.RobRedPacketEntity;
import com.fernfx.xingtan.main.model.ChatModel;
import com.fernfx.xingtan.user.AccountManager;
import com.fernfx.xingtan.utils.FastJsonUtil;
import com.fernfx.xingtan.utils.LogUtils;
import com.fernfx.xingtan.utils.OtherUtil;
import com.fernfx.xingtan.utils.ToastUtil;

import java.util.List;
import java.util.Map;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

/**
 * Created by admin on 2018/8/9.
 */

public class ChatPresenter<P extends ChatContract.View> implements ChatContract.Presenter{
    private P P;
    private ChatContract.Model model;

    @Override
    public void init(ChatContract.View view) {
        this.P = (P) view;
        model = new ChatModel();
    }

    @Override
    public void isReconnect(Intent intent) {
        //push，通知或新消息过来
        if (intent != null && intent.getData() != null && intent.getData().getScheme().equals("rong")) {
            String token = AccountManager.getUserInfo().getObj().getRongCloudToken();
            //通过intent.getData().getQueryParameter("push") 为true，判断是否是push消息
            if (intent.getData().getQueryParameter("push") != null
                    && intent.getData().getQueryParameter("push").equals("true")) {

                reconnect(token);
            } else {
                //程序切到后台，收到消息后点击进入,会执行这里
                if (RongIM.getInstance() == null || RongIM.getInstance().getRongIMClient() == null) {

                    reconnect(token);
                } else {
                    enterFragment();
                }
            }
        }
    }

    @Override
    public void requestRobRedPacket(Map<String, Object> requestArgsMap) {
        model.requestRobRedPacket(requestArgsMap, new IRequestCallback() {
            @Override
            public void onSuccessful(NetworkOKResult result) {
                String message = result.getMessage();
                if (TextUtils.isEmpty(message)) {
                    onNetworkError(result.getMessage(),500);
                    return;
                }
                RobRedPacketEntity robRedPacketEntity = FastJsonUtil.fromBean(message, RobRedPacketEntity.class);
                if (null != robRedPacketEntity && OtherUtil.checkRequestStatus(robRedPacketEntity.getSuccess(),robRedPacketEntity.getStatus())) {
                    List<RobRedPacketEntity.ObjBean.RecordsBean> recordsBeanList = robRedPacketEntity.getObj().getRecords();
                    //设置圆的大小
                    P.setCircleScope(robRedPacketEntity.getObj().getRange());
                    //设置红包
                    P.getChatFragment().showRobRedPacket(recordsBeanList);
                }
            }

            @Override
            public void onFailure(String errorMessage, int errorCode) {
                if (TextUtils.isEmpty(errorMessage)) {
                    onNetworkError(errorMessage,errorCode);
                    return;
                }

                final BaseEntity baseEntity = FastJsonUtil.fromBean(errorMessage, BaseEntity.class);
                if (null != baseEntity && !TextUtils.isEmpty(baseEntity.getMsg())){
                    ToastUtil.showCentertoast(baseEntity.getMsg());
                }
            }

            @Override
            public void onNetworkError(String errorMessage, int errorCode) {
                ToastUtil.showCentertoast(R.string.network_error);
            }
        });
    }

    /**
     * 重连
     *
     * @param token
     */
    public void reconnect(String token) {

        if (ConsumerApplication.getInstance().getApplicationInfo().packageName.equals(OtherUtil.getCurProcessName(ConsumerApplication.getInstance().getApplicationContext()))) {

            RongIM.connect(token, new RongIMClient.ConnectCallback() {
                @Override
                public void onTokenIncorrect() {

                }

                @Override
                public void onSuccess(String s) {

                    enterFragment();
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {

                }
            });
        }
    }

    /**
     * 加载 会话列表 ConversationListFragment
     */
    public void enterFragment() {
        Uri uri = Uri.parse("rong://" + ConsumerApplication.getInstance().getApplicationInfo().packageName).buildUpon()
                .appendPath("conversationlist")
                .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false") //设置私聊会话非聚合显示
                .appendQueryParameter(Conversation.ConversationType.GROUP.getName(), "true")//设置群组会话聚合显示
                .appendQueryParameter(Conversation.ConversationType.DISCUSSION.getName(), "false")//设置讨论组会话非聚合显示
                .appendQueryParameter(Conversation.ConversationType.SYSTEM.getName(), "false")//设置系统会话非聚合显示
                .build();

        P.getConversationListFragment().setUri(uri);
    }
}
